#!/usr/bin/env python3
import smtplib
import pymysql
from email.mime.text import MIMEText
from datetime import datetime

# 配置参数
MASTER_CONFIG = {
    'host': '主库IP',
    'port': 3306,
    'user': '监控用户',
    'password': '密码',
    'charset': 'utf8'
}

SLAVE_CONFIG = {
    'host': '从库IP',
    'port': 3306,
    'user': '监控用户',
    'password': '密码',
    'charset': 'utf8'
}

EMAIL_CONFIG = {
    'smtp_server': 'smtp.example.com',
    'smtp_port': 25,
    'sender': 'sender@example.com',
    'receiver': 'receiver@example.com',
    'username': 'smtp用户名',
    'password': 'smtp密码'
}

def check_replication_status():
    try:
        # 连接从库检查复制状态
        slave_conn = pymysql.connect(**SLAVE_CONFIG)
        with slave_conn.cursor() as cursor:
            cursor.execute("SHOW SLAVE STATUS")
            slave_status = cursor.fetchone()

        if not slave_status:
            return False, "无法获取从库状态"

        # 获取关键状态指标
        io_running = slave_status[10]  # Slave_IO_Running
        sql_running = slave_status[11] # Slave_SQL_Running
        seconds_behind = slave_status[32] # Seconds_Behind_Master
        last_error = slave_status[19] # Last_Error

        if io_running != 'Yes' or sql_running != 'Yes':
            error_msg = f"复制中断: IO线程状态={io_running}, SQL线程状态={sql_running}"
            if last_error:
                error_msg += f", 错误信息: {last_error}"
            return False, error_msg

        if seconds_behind is not None and seconds_behind > 60:
            return False, f"主从延迟超过阈值: {seconds_behind}秒"

        return True, "复制状态正常"

    except Exception as e:
        return False, f"检查复制状态时出错: {str(e)}"
    finally:
        if 'slave_conn' in locals():
            slave_conn.close()

def send_alert_email(subject, message):
    try:
        msg = MIMEText(message, 'plain', 'utf-8')
        msg['Subject'] = subject
        msg['From'] = EMAIL_CONFIG['sender']
        msg['To'] = EMAIL_CONFIG['receiver']

        with smtplib.SMTP(EMAIL_CONFIG['smtp_server'], EMAIL_CONFIG['smtp_port']) as server:
            if EMAIL_CONFIG.get('username'):
                server.login(EMAIL_CONFIG['username'], EMAIL_CONFIG['password'])
            server.sendmail(EMAIL_CONFIG['sender'], [EMAIL_CONFIG['receiver']], msg.as_string())
        print(f"告警邮件已发送: {subject}")
    except Exception as e:
        print(f"发送邮件失败: {str(e)}")

if __name__ == '__main__':
    is_ok, status_msg = check_replication_status()
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    if not is_ok:
        subject = f"[MySQL复制告警] {current_time}"
        message = f"""
MySQL主从复制状态异常:

{status_msg}

主库: {MASTER_CONFIG['host']}
从库: {SLAVE_CONFIG['host']}
检测时间: {current_time}
"""
        send_alert_email(subject, message)
    else:
        print(f"{current_time} - 复制状态正常: {status_msg}")
